package com.grouuu.media;
import com.grouuu.data.MapData;
import haxe.Http;
import js.Browser;
import js.html.Event;
import js.html.ImageElement;

/**
 * ...
 * @author Grouuu
 */
class LoadMedia
{
	private var cb_mapImage_success:ImageElement->Void;
	private var cb_mapImage_error:String->Void;
	private var mapImage:ImageElement;
	
	private var cb_mapData_success:MapData->Void;
	private var cb_mapData_error:String->Void;
	private var requestData:Http;

	public function new() 
	{
		
	}
	
	// IMAGE //////////////////////////////////////////////////////////////////////////////////////
	
	public function loadMapImage(onLoaded:ImageElement->Void, onError:String->Void)
	{
		cb_mapImage_success = onLoaded;
		cb_mapImage_error = onError;
		
		mapImage = Browser.document.createImageElement();
		mapImage.onload = onMapImageLoaded;
		mapImage.onerror = onMapImageError;
		mapImage.src = "img/map.png";
	}
	
	private function onMapImageLoaded(e:Event):Void
	{
		cb_mapImage_success(mapImage);
		
		resetMapImage();
	}
	
	private function onMapImageError(e:Event):Void
	{
		cb_mapImage_error("Erreur lors du chargement de l'image 'map.png'");
		
		resetMapImage();
	}
	
	private function resetMapImage():Void
	{
		mapImage = null;
		cb_mapImage_success = null;
		cb_mapImage_error = null;
	}
	
	// DATA ///////////////////////////////////////////////////////////////////////////////////////
	
	public function loadMapData(onLoaded:MapData->Void, onError:String->Void):Void
	{
		cb_mapData_success = onLoaded;
		cb_mapData_error = onError;
		
		requestData = new Http("img/map.html");
		
		requestData.onData = onMapDataLoaded;
		requestData.onError = onMapDataError;
		
		requestData.request(false);
	}
	
	private function onMapDataLoaded(data:String):Void
	{
		var mapData:MapData = new MapData(data);
		
		cb_mapData_success(mapData);
		
		resetMapData();
	}
	
	private function onMapDataError(message:String):Void
	{
		cb_mapData_error("Erreur lors du chargement du fichier 'map.html' : " + message);
		
		resetMapData();
	}
	
	private function resetMapData():Void
	{
		requestData = null;
		cb_mapData_success = null;
		cb_mapData_error = null;
	}
}